package back.config;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

// 拦截器
public class MyInterceptor implements HandlerInterceptor {
    // 处理前
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        System.out.println("==========拦截了=============");
//        System.out.println(request.getRequestURI());

        if (session.getAttribute("user") != null && request.getRequestURI().contains("login")) {
            response.sendRedirect(request.getContextPath() + "/admin/index");
            return false;
        }


        if (request.getRequestURI().contains("login")) {
            return true;
        }

        if (session.getAttribute("user") != null) {
            return true;
        }

        response.sendRedirect(request.getContextPath() + "/login");
        return false;
    }

    // 处理后
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    // 清理
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
